package socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author DCSGO
 * @version 1.0
 * 客户端
 * 向服务端发送“Hello,Server",并接收
 * 服务端回发的“Hello,Client"
 */
public class SocketTCP02Client {
    public static void main(String[] args) {
        int port = 9999;
        Socket socket = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //InetAddress serverInetAddress = InetAddress.getLocalHost();
            InetAddress serverInetAddress = InetAddress.getByName("47.113.198.9");
            System.out.println("已获取到服务端 InetAddress !");
            socket = new Socket(serverInetAddress, port);
            outputStream = socket.getOutputStream();
            System.out.println("正在向客服端发送数据...");
            outputStream.write("Hello,Server".getBytes());
            socket.shutdownOutput();//设置写入结束标记 不能直接 outputStream.close()
            System.out.println("数据发送完成!");
            inputStream = socket.getInputStream();
            System.out.println("正在读取客服端回传的数据...");
            int readLen;
            byte[] data = new byte[1024];
            while ((readLen = inputStream.read(data)) != -1) {
                System.out.println(new String(data, 0, readLen));
            }
            System.out.println("服务端回传的数据读取完毕!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                if (socket != null) {
                    socket.close();
                }
                System.out.println("相关资源已关闭 程序退出...");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /*
     * 已获取到服务端 InetAddress !
     * 正在向客服端发送数据...
     * 数据发送完成!
     * 正在读取客服端回传的数据...
     * Hello,Client
     * 服务端回传的数据读取完毕!
     * 相关资源已关闭 程序退出...
     *
     * 进程已结束，退出代码为 0
     */
}
